/*
 * @Author: Leo.wang wanglizhigs@163.com
 * @Date: 2024-06-03 22:57:27
 * @LastEditors: Leo.wang wanglizhigs@163.com
 * @LastEditTime: 2024-06-29 00:07:19
 * @FilePath: /chat-ai-plus/src/store/modules/robot.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia';
import { sleep } from '@/utils/utility';
import {
  getTopicList,
  createTopic,
  updateTopic,
  removeTopic,
  getConversationsById,
  generateText,
  sendMessage,
  generateImage,
  uploadFile,
  collectTopic,
  unCollectTopic
} from '@/api/chat.api';
import { aiModels } from '@/model';
import emitter from '@/utils/emitter';

const useChatStore = defineStore({
  id: 'chatStore',
  state: () => ({
    currentModel: aiModels[0],
    historyTopics: [],
    conversations: [],
    currentRoom: undefined,
    sending: false,
    isConversation: false,
  }),
  getters: {},
  actions: {
    setSending(state) {
      this.sending = state
    },

    async getTopicList(params) {
      const response = await getTopicList(params);
      const { data } = response;
      if(params.page === 0 ) {
        this.historyTopics = data.content;
      }else {
        if (data && data.content) {
          this.historyTopics = [...this.historyTopics, ...data.content];
        }
      }
     
      return response;
    },
    async refreshTopicList(params) {
      const response = await getTopicList(params);
      const { data } = response;
      if (data && data.content) {
        this.historyTopics = data.content;
      }
      return response;
    },
    async createTopic() {
      const result = await createTopic();

      return result;
    },
    clearTopic() {
      this.historyTopics = [];
    },

    clearConversations() {
      this.conversations = [];
    },
    async updateTopic() {
      const result = await updateTopic();

      return result;
    },
    removeTopic(id) {
      removeTopic([id]).then(() => {
        this.historyTopics = this.historyTopics.filter((item) => item.id !== id)
      });
    },

    setCurrentRoom(state = undefined) {
      this.currentRoom = state;
    },
    toggleModel(state) {
      this.currentModel = [...aiModels].find(model => model.value === state);
    },

    collectTopic(id) {
      collectTopic(id)
    },

    unCollectTopic(id) {
      unCollectTopic(id).then(() => {
        this.historyTopics = this.historyTopics.filter(topic => topic.id !== id)
      })
    },

    

    async getConversationsById(params) {
      const response = await getConversationsById(params);
      const { data } = response;
      this.conversations = data.content || [];
      return response;
    },
    async generate(params) {
      this.isConversation = true;
      if (!this.currentRoom) {
        const { data } = await createTopic({ version: this.currentModel.version });
        this.currentRoom = {
          id: data,
        };
      }
      const firstMessage = this.conversations.length === 0;

      this.conversations.unshift({
        context: params.msg,
        fileList: params.addFileList,
        roomId: this.currentRoom.id,
        type: params.type,
        role: 'USER',
      });
      console.log(' this.conversations',  this.conversations)

      if (this.currentModel.name === 'DALL·E') {
        this.generateImage({ ...params, firstMessage });
      } else {
        this.generateText({ ...params, firstMessage });
      }
      this.sending = false
    },
    async generateImage(params) {
      const imageResult = {
        context: '',
        fileList: [],
        roomId: this.currentRoom.id,
        type: params.type,
        role: 'CHAT',
      };

      this.conversations.unshift(imageResult);

      generateImage({
        ...params,
        roomId: this.currentRoom.id,
        version: this.currentModel?.version,
      }).then(response => {
        const fileList = response.data.data.map(item => ({
          fileUrl: item.url,
          type: 0,
          prompt: item.revisedPrompt,
        }));
        this.conversations.shift();
        this.conversations.unshift({
          ...imageResult,
          fileList,
        });
       
        this.getConversationsById({ roomId: this.currentRoom.id }).then(
          () => {
            if (params.firstMessage) {
              emitter.emit('refreshTopic')
            }
            this.isConversation = false
          }
        );
      });
    },

    async generateText(params) {
      sendMessage(
        {
          ...params,
          roomId: this.currentRoom.id,
          version: this.currentModel?.version,
        },
        message => {
          if (!message) {
            
            this.getConversationsById({ roomId: this.currentRoom.id }).then(
              () => {
                if (params.firstMessage) {
                  emitter.emit('refreshTopic')
                }
                this.isConversation = false;
              }
            );
           
            return;
          }
          const { finish_reason, choices } = message;
          if (this.conversations[0].role === 'USER') {
            this.conversations.unshift({
              context: '',
              fileList: [],
              roomId: this.currentRoom.id,
              type: params.type,
              role: 'CHAT',
            });
          }
          choices.forEach(item => {
            if (item.finish_reason !== 'stop') {
              this.conversations[0].context += `${item.delta.content}`;
            }
          });
        }
      );
    },

    async uploadFile(params) {
      // if (!this.currentRoom) {
      //   const { data } = await createTopic({ version: this.currentModel.version });
      //   this.currentRoom = {
      //     id: data,
      //   };
      // }
      return await uploadFile({
        ...params,
        name: 'file',
        formData: { roomId: this.currentRoom?.id },
      });
    },


  },
  persist: {
    enabled: true,
    strategies: [
      {
        storage: sessionStorage,
        paths: ['currentRoom', 'currentModel'],
      },
    ],
  },
});
export default useChatStore;

